package com.hongye.why.module;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hongye.why.MainActivity;
import com.hongye.why.R;
import com.hongye.why.app.AppManager;
import com.hongye.why.base.BaseActivity;
import com.hongye.why.base.ParamsFactory;
import com.hongye.why.base.TaskPool;
import com.hongye.why.base.net.CommonResponse;
import com.hongye.why.base.net.IRequest;
import com.hongye.why.base.net.OKManager;
import com.hongye.why.model.Field;
import com.hongye.why.model.LoginInfo;
import com.hongye.why.test.TestActivity;
import com.hongye.why.util.DialogUtil;
import com.hongye.why.util.PreferenceUtil;
import com.igexin.sdk.PushManager;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 登录界面
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener,View.OnLayoutChangeListener {
    @Bind(R.id.btn_login)
    Button loginBtn;  //登录按钮
    @Bind(R.id.tv_forget_password)
    TextView forgetPwdTv;  //忘记密码
    @Bind(R.id.et_login_name)
    EditText loginNameEt;  //用户名
    @Bind(R.id.et_login_password)
    EditText pwdEt;  //密码
    @Bind(R.id.sv_login)
    ScrollView scrollview;

    private String userAccount;

    private String loginName;
    private String pwd;
    private int keyHeight;
    private TextView registerTxt;

    @Override
    public int inflateLayout() {
        return R.layout.activity_user_login;
    }

    @Override
    public void onCreate() {
        ButterKnife.bind(this);

        //获取屏幕高度
        int screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight/3;
        showTitle(false);
        Intent intent = getIntent();
        userAccount = intent.getStringExtra("userAccount");
        boolean isPushOut = intent.getBooleanExtra("pushOut", false);

        setupViews();

        if (isPushOut) {
//            displayLogout();
        } else {
            Uri fileUri = intent.getData();
            if (fileUri != null) {
                installApk(getIntent().getData());
            }
        }
    }

    /**
     * 初始化
     */
    private void setupViews() {

        forgetPwdTv.addOnLayoutChangeListener(this);

        if (!TextUtils.isEmpty(userAccount)) {
            loginNameEt.setText(userAccount);
        }

        loginBtn.setOnClickListener(this);

        forgetPwdTv.setClickable(true);
        forgetPwdTv.setOnClickListener(this);
        registerTxt = (TextView) findViewById(R.id.tv_register);
        registerTxt.setOnClickListener(this);
        LinearLayout rootLl = (LinearLayout) findViewById(R.id.ll_login_root);
        rootLl.addOnLayoutChangeListener(this);
    }

    /**
     * 登录
     */
    private void doLogin() {
        loginName = loginNameEt.getText().toString();
        pwd = pwdEt.getText().toString();
        String cid = PushManager.getInstance().getClientid(getApplicationContext());
        if (TextUtils.isEmpty(cid)) {
            cid = PreferenceUtil.getPrefString(this,"getui_cid","");
        }

        OKManager okManager = OKManager.getManager();
        IRequest iRequest = okManager.addRequest(this, ParamsFactory.getLoginParams(loginName, pwd, cid));
        iRequest.execute(new CommonResponse() {
            @Override
            public void onNetStart() {
                DialogUtil.showLoading(LoginActivity.this, "正在登录...", false);
            }

            @Override
            public Object parseResult(String result) {
                LoginInfo loginInfo = JSON.parseObject(result, LoginInfo.class);
                return loginInfo;
            }

            @Override
            public void onSuccess(Object result) {
                LoginInfo loginInfo = (LoginInfo) result;
                Field field = new Field();
                field.fieldType = loginInfo.fieldType;
                field.phValue = loginInfo.phValue;
                field.youjiValue = loginInfo.youjiValue;
                AppManager.getManager().getUserSession().setUser(loginName, pwd, loginInfo.accessToken, loginInfo.userInfo, field);
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }

            @Override
            public void onEnd() {
                DialogUtil.dismissLoading();
            }
        });
    }

    /**
     * 校验用户名和密码是否输入
     * @return boolean
     */
    private boolean checkLoginNameAndPwd() {
        if (TextUtils.isEmpty(loginNameEt.getText().toString().trim())) {
            Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
            return false;
        } else if (TextUtils.isEmpty(pwdEt.getText().toString().trim())) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        switch (viewId) {
            case R.id.btn_login:  // 登录
                if (checkLoginNameAndPwd()) {
                    doLogin();
                }
                break;
            case R.id.tv_forget_password:  // 忘记密码
                break;
            case R.id.tv_register://注册
                Intent intent = new Intent(LoginActivity.this, TestActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    //安装apk
    protected void installApk(Uri fileUri) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        // 如果不加无法正常显示安装过程和安装成功提示
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //执行的数据类型
        intent.setDataAndType(fileUri, "application/vnd.android.package-archive");//编者按：此处Android应为android，否则造成安装不了
        startActivity(intent);
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
        if(oldBottom != 0 && bottom != 0 &&(oldBottom - bottom > keyHeight)){

            scrollToBottom();

        }else if(oldBottom != 0 && bottom != 0 &&(bottom - oldBottom > keyHeight)){

//            Toast.makeText(LoginActivity.this, "监听到软件盘关闭...", Toast.LENGTH_SHORT).show();

        }
    }

    protected void scrollToBottom() {
        TaskPool.myPool().postTaskOnMainDelay(new Runnable() {
            @Override
            public void run() {
                scrollview.scrollTo(0,scrollview.getBottom());
//                scrollview.fullScroll(View.FOCUS_DOWN);
            }
        }, 100);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
